package com.cyl.h5.controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyl.h5.config.SecurityUtil;
import com.cyl.h5.domain.form.AddAcForm;
import com.cyl.h5.domain.form.ApplyRefundForm;
import com.cyl.h5.domain.vo.H5AddressVO;
import com.cyl.h5.domain.vo.H5OrderVO;
import com.cyl.h5.service.H5CouponActivityService;
import com.cyl.h5.service.H5MemberService;
import com.cyl.h5.service.H5OrderService;
import com.cyl.manager.act.domain.entity.CouponActivity;
import com.cyl.manager.act.domain.entity.CouponCategory;
import com.cyl.manager.act.domain.entity.IntegralHistory;
import com.cyl.manager.act.domain.query.CouponActivityQuery;
import com.cyl.manager.act.domain.query.CouponActivitySy;
import com.cyl.manager.act.domain.query.MemberCouponQuery;
import com.cyl.manager.act.domain.query.MemberCouponTjQuery;
import com.cyl.manager.act.domain.vo.CouponActivityVO;
import com.cyl.manager.act.domain.vo.MemberCouponTjVO;
import com.cyl.manager.act.mapper.CouponCategoryMapper;
import com.cyl.manager.act.mapper.MemberCouponMapper;
import com.cyl.manager.act.pojo.dto.CouponCategoryDTO;
import com.cyl.manager.act.service.CouponActivityService;
import com.cyl.manager.act.service.CouponCategoryService;
import com.cyl.manager.act.service.IntegralHistoryService;
import com.cyl.manager.act.service.MemberCouponService;
import com.cyl.manager.aws.convert.ShopStatistics2Convert;
import com.cyl.manager.aws.convert.SystemStatistics2Convert;
import com.cyl.manager.aws.domain.entity.ShopStatistics;
import com.cyl.manager.aws.domain.entity.SystemStatistics;
import com.cyl.manager.aws.domain.query.SystemStatisticsQuery;
import com.cyl.manager.aws.pojo.query.ShopStatisticsQuery;
import com.cyl.manager.aws.service.ShopStatisticsService;
import com.cyl.manager.aws.service.SystemStatisticsService;
import com.cyl.manager.oms.domain.entity.Order;
import com.cyl.manager.oms.domain.entity.OrderItem;
import com.cyl.manager.oms.domain.entity.OrderItemPrepare;
import com.cyl.manager.oms.domain.form.DealWithAftersaleForm;
import com.cyl.manager.oms.domain.form.ManagerOrderQueryForm;
import com.cyl.manager.oms.domain.form.OrderItemPrepareFrom;
import com.cyl.manager.oms.domain.query.OrderItemDptjQuery;
import com.cyl.manager.oms.domain.query.OrderItemPrepareQuery;
import com.cyl.manager.oms.domain.vo.ManagerOrderVO;
import com.cyl.manager.oms.domain.vo.OrderItemDptjVO;
import com.cyl.manager.oms.domain.vo.OrderItemPrepareExcelVO;
import com.cyl.manager.oms.mapper.OrderMapper;
import com.cyl.manager.oms.service.AftersaleService;
import com.cyl.manager.oms.service.OrderItemPrepareService;
import com.cyl.manager.oms.service.OrderItemService;
import com.cyl.manager.oms.service.OrderService;
import com.cyl.manager.ums.domain.entity.Feedback;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.ums.domain.entity.MemberAccount;
import com.cyl.manager.ums.domain.query.FeedbackQuery;
import com.cyl.manager.ums.domain.query.MemberQuery;
import com.cyl.manager.ums.domain.query.MemberTopQuery;
import com.cyl.manager.ums.domain.vo.MemberTopVO;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.cyl.manager.ums.service.FeedbackService;
import com.cyl.manager.ums.service.MemberAccountService;
import com.cyl.manager.ums.service.MemberService;
import com.cyl.manager.ums.service.MemberTbService;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.redis.RedisService;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.framework.config.LocalDataUtil;
import com.ruoyi.livesass.api.mapper.LbsGkscMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysDeptService;

import cn.hutool.core.date.DateUtil;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/h5/shop")
@Slf4j
public class H5ShopController {
	
    @Autowired
    private LbsGkscMapper lbsGkscMapper;

	@Autowired
	private MemberService memberService;
	  
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private OrderMapper orderMapper;
	   
    @Autowired
    private H5OrderService h5OrderService;
    
    @Autowired
    private RedisService redisService;
    
    @Autowired
    private MemberCouponService memberCouponService;
    
    @Autowired
    private OrderItemPrepareService orderItemPrepareService;
    
    @Autowired
    private ISysDeptService deptService;
    
    @Autowired
    private OrderItemService orderItemService;
    
    @Autowired
    private IntegralHistoryService integralHistoryService;
    
    @Autowired
    private RedisCache redisCache;
    
    @Autowired
    private SystemStatisticsService systemStatisticsService;
    
    @Autowired
    private ShopStatisticsService shopStatisticsService;
    
    @Autowired
    private CouponActivityService couponActivityService;
    
    @Autowired
    private MemberAccountService memberAccountService;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    
    @Autowired
    private  MemberCouponMapper memberCouponMapper;
    
	@Autowired
	private FeedbackService feedbackService;
	

    @Autowired
    private H5MemberService h5MemberService;
    
    @Autowired
    private CouponCategoryMapper couponCategoryMapper;
    
    @Autowired
    private CouponCategoryService couponCategoryService;
    
    @Autowired
    private MemberMapper memberMapper;
    
    @Autowired
    private H5CouponActivityService h5CouponActivityService;
    
    @Autowired
    private SysDeptMapper deptMapper;

    
    @Autowired
    private AftersaleService aftersaleService;
    
    @Autowired
    private MemberTbService memberTbService;
    

    
    
    public static Long getSpreaduid() {
        Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        int rolezd = member.getRolezd().intValue();//0->普通用户；1->核销员；2->团长 3 副店长 4 群主
        if(rolezd == 2 || rolezd == 3 || rolezd == 1) {
        	return null;
        }
    	return member.getId();
    }
    
    
    //@ApiOperation("查询会员信息列表")
    @PostMapping("/ums/member/list")
    public ResponseEntity<Page<Member>> list(@RequestBody MemberQuery query, Pageable page) {
        Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        Long deptDpId = member.getDeptDpId();
    	query.setDeptDpId(deptDpId);
    	Long spreaduid = query.getSpreaduid(); 
    	if(spreaduid!=null) {
    		query.setSpreaduid(spreaduid);
    	}else {
    		query.setSpreaduid(getSpreaduid());
    	}
        List<Member> list = memberService.selectList(query, page);
        return ResponseEntity.ok(new PageImpl<>(list, page, ((com.github.pagehelper.Page)list).getTotal()));
    }
    
    
    //@ApiOperation("查询会员排名") /h5/shop
    @PostMapping("/ums/member/listByTop")
    public ResponseEntity<Page<MemberTopVO>> listByTop(@RequestBody MemberTopQuery query, Pageable page) {
        Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        Long deptDpId = member.getDeptDpId();
        if(deptDpId==null) {
            throw new RuntimeException("权限不足");
        }
    	query.setDeptDpId(deptDpId);
    	Long spreaduid = query.getSpreaduid(); 
    	if(spreaduid!=null) {
    		query.setSpreaduid(spreaduid);
    	}else {
    		query.setSpreaduid(getSpreaduid());
    	}
    	List<MemberTopVO> list = memberService.listByTop(query, page);
        return ResponseEntity.ok(new PageImpl<>(list, page, ((com.github.pagehelper.Page)list).getTotal()));
    }
    
    
    //@ApiOperation("修改会员状态")  参数 id hyzt 会员状态  0正常 1禁言 2拉黑
    //   /h5/shop
    @PostMapping("/ums/member/updateHyzt")
    public ResponseEntity<Integer> list(@RequestBody MemberQuery query) {
    	Member member = memberService.selectById(Long.parseLong(query.getId()));
    	if(member==null) {
            throw new RuntimeException("会员id:" +query.getId()+"不存在！");
    	}
    	if(query.getHyzt() == null) {
            throw new RuntimeException("会员状态不能为空");
    	}
    	checkMember(member.getId());
    	String memberKey = Constants.MEMBER_INFO+"_"+member.getId();
	    redisCache.deleteObject(memberKey);
    	member.setHyzt(query.getHyzt());
        member.setUpdateTime(LocalDateTime.now());
        return ResponseEntity.ok(memberService.update(member));
    }
    
    
 
    
    
    //@ApiOperation("查询订单表列表")
    @PostMapping("/oms/order/list")
    public ResponseEntity<Page<ManagerOrderVO>> list(@RequestBody ManagerOrderQueryForm query, Pageable page) {
    	Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        Long deptDpId = member.getDeptDpId();
     	query.setDeptDpId(deptDpId);
    	Long spreaduid = query.getSpreaduid(); 
    	if(spreaduid!=null) {
    		query.setSpreaduid(spreaduid);
    	}else {
    		query.setSpreaduid(getSpreaduid());
    	}
     	return ResponseEntity.ok(orderService.selectList(query, page));
    }
    
    //@ApiOperation("查询订单表详情")
    @PostMapping("/oms/order/detail")
    public ResponseEntity<ManagerOrderVO> orderDetail(@RequestBody Long orderId) {
    	if(orderId==null) {
            throw new RuntimeException("orderId id不能为空");
    	}
    	ManagerOrderQueryForm query = new ManagerOrderQueryForm();
    	query.setOrderId(orderId);
    	Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        Long deptDpId = member.getDeptDpId();
     	query.setDeptDpId(deptDpId);
     	PageImpl<ManagerOrderVO> page =	orderService.selectList(query, null);
     	if(page!=null && page.getContent()!=null && page.getContent().size()>0) {
     		ManagerOrderVO managerOrderVO = page.getContent().get(0);
     		  if(managerOrderVO.getCplx()!=null && managerOrderVO.getDhCouponCategoryId()!=null) {
     	        	CouponCategory couponCategory = couponCategoryService.selectCheckById(managerOrderVO.getDhCouponCategoryId());
     	        	if(couponCategory!=null) {
     	        		managerOrderVO.setDhCouponCategoryMc(couponCategory.getTitle());
     	        	}
     	        }
     		return ResponseEntity.ok(managerOrderVO);
     	}
     	return ResponseEntity.ok(new ManagerOrderVO());
    }
    
    
 
    @ApiOperation("订单列表")
    @GetMapping("/oms/orderMember/list")
    public ResponseEntity<PageImpl<H5OrderVO>> orderPage(String lockIdNotIsNull,String lockIdIsNull,Long memberId,Integer sendGysStatus,Integer status,String keyword, Pageable pageable){
        
    	Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        Long deptDpId = member.getDeptDpId();
        if(memberId==null) {
        	return ResponseEntity.ok(new PageImpl<H5OrderVO>(new ArrayList<H5OrderVO>()));
        }
        Member memberKh = memberService.selectById(memberId);
        if(memberKh == null || !deptDpId.equals(memberKh.getDeptDpId())) {
        	return ResponseEntity.ok(new PageImpl<H5OrderVO>(new ArrayList<H5OrderVO>()));
        }

        return ResponseEntity.ok(h5OrderService.orderPage(lockIdNotIsNull,lockIdIsNull,sendGysStatus,status, memberId,keyword, pageable));
    }
    
    
    

    //@ApiOperation("确认到货")
    @PostMapping("/oms/orderMember/complete")
    public ResponseEntity<String> orderMemberComplete(@RequestBody Long orderItemPrepareId) {
        
        OrderItemPrepare orderItemPrepare = orderItemPrepareService.selectById(orderItemPrepareId);
        if(orderItemPrepare==null) {
            throw new RuntimeException("未查询到订单信息");
        }
        if(!"3".equals(orderItemPrepare.getBhZt())) {
            throw new RuntimeException("未发货或已签收，不能签收");
        }
        Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        Long deptDpId = member.getDeptDpId();
        Long orderDeptDpId= orderItemPrepare.getDeptDpId();
        if(orderDeptDpId == null || !deptDpId.equals(orderDeptDpId)) {
            throw new RuntimeException("非本店铺信息不能操作");
        }
        LocalDateTime localDateTime = LocalDateTime.now();
        OrderItemPrepareFrom orderItemPrepareUpate =  new OrderItemPrepareFrom();
        orderItemPrepareUpate.setId(orderItemPrepareId);
        orderItemPrepareUpate.setBhZt("4");
        orderItemPrepareUpate.setUpdateTime(localDateTime);
        orderItemPrepareUpate.setQsTime(localDateTime);
        orderItemPrepareUpate.setMemberId(member.getId());
        orderItemPrepareService.updateBhZt(orderItemPrepareUpate);
        return ResponseEntity.ok("成功");

    }
    
    
    //@ApiOperation("查询备货管理列表")
    @PostMapping("/oms/orderPrepare/list")
    public ResponseEntity<Page<OrderItemPrepareExcelVO>> list(@RequestBody OrderItemPrepareQuery query, Pageable page) {
       	Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        Long deptDpId = member.getDeptDpId();
    	query.setDeptDpId(deptDpId);
    	Map<String, Object> map = orderItemPrepareService.selectListByExcel(query, page);
        List<OrderItemPrepareExcelVO> list = (List<OrderItemPrepareExcelVO>) map.get("list");
        return ResponseEntity.ok(new PageImpl<OrderItemPrepareExcelVO>(list, page, (long)map.get("count")));
    }
    
    
    //@ApiOperation("根据id查询查询备货管理列表")
    @PostMapping("/oms/orderPrepare/detail")
    public ResponseEntity<OrderItemPrepareExcelVO> orderPrepareDetail(@RequestBody Long orderItemPrepareId) {
    	if(orderItemPrepareId==null) {
            throw new RuntimeException("店铺订单id不能为空");
    	}
       	Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        Long deptDpId = member.getDeptDpId();
        OrderItemPrepareQuery query = new OrderItemPrepareQuery();
        query.setId(orderItemPrepareId);
    	query.setDeptDpId(deptDpId);
    	Map<String, Object> map = orderItemPrepareService.selectListByExcel(query, null);
        List<OrderItemPrepareExcelVO> list = (List<OrderItemPrepareExcelVO>) map.get("list");
        if(list!=null && list.size()>0) {
            return ResponseEntity.ok(list.get(0));
        }
        return ResponseEntity.ok(new OrderItemPrepareExcelVO());
    }
    
    
    
    //@ApiOperation("确认收货")
    @PostMapping("/oms/order/complete")
    public ResponseEntity<String> orderComplete(@RequestBody Long orderId) {
        log.info("确认收货，订单id："+orderId);
        Order order = orderMapper.selectById(orderId);
        if(order==null) {
            throw new RuntimeException("未查询到订单信息");
        }
        Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        Long hxmemberid  = member.getId();
        String hxmembernc = member.getNickname();
        Long deptDpId = member.getDeptDpId();
        
        
        Long memberId = order.getMemberId();
        Member memberKh = memberService.selectById(memberId);
        if(memberKh == null || !deptDpId.equals(memberKh.getDeptDpId())) {
            throw new RuntimeException("非本店铺信息不能核销");
        }
        
        
        int rolezd = member.getRolezd().intValue();//0->普通用户；1->核销员；2->团长 3 副店长 4 群主
        if(rolezd == 4) {// 4 群主
        	if(!hxmemberid.equals(memberKh.getSpreaduid()) ) {
                throw new RuntimeException("店员只能核销自己会员的订单");
            }
        }
        

        String redisKey = "h5_oms_order_complete_"+orderId;
        String redisValue = orderId+"_"+System.currentTimeMillis();
        try{
            redisService.lock(redisKey,redisValue,60);
            return ResponseEntity.ok(h5OrderService.orderComplete(orderId,hxmemberid,hxmembernc));
        }catch (Exception e){
            log.error("确认收货异常",e);
            throw new RuntimeException(e.getMessage());
        }finally {
            try{
                redisService.unLock(redisKey,redisValue);
            }catch (Exception e){
                log.error("",e);
            }
        }
    }
    
    
    @ApiOperation("使用优惠券")
    @PostMapping("/act/memberCoupon/exchangeCoupon")
    public ResponseEntity<Boolean> exchangeCoupon(@RequestBody CouponActivitySy query) {
        //获取所有未过期且运行中的活动
    	checkMember(query.getMemberId());
        Member memberDz = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        int rolezd = memberDz.getRolezd().intValue();
        if(rolezd == 4) {// 4 群主
            Member memberKh = memberService.selectById(query.getMemberId());
        	if(!memberDz.getId().equals(memberKh.getSpreaduid()) ) {
                throw new RuntimeException("店员只能核销自己会员的福利券");
            }
        }
        
        return ResponseEntity.ok(memberCouponService.exchangeCouponByH5(query));
    }
    
    @ApiOperation("查询用户优惠券聚合活动列表")
    @PostMapping("/act/couponCategorylist")
    public ResponseEntity<List<CouponCategoryDTO>> couponCategorylist(@RequestBody MemberCouponQuery query) {
        //获取所有未过期且运行中的活动
    	checkMember(query.getMemberId());
    	if(query.getType()==null) {
    		query.setType(1);
    	}
        return ResponseEntity.ok(memberCouponService.selectListGrepByH5(query));
    }
    
    @ApiOperation("修改用户角色")
    @PutMapping("/ums/member/updateByJs")
    public ResponseEntity<Integer> updateByDz(@RequestBody Member member) {
    	checkMember(member.getId());
        Member memberDz = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        return    ResponseEntity.ok(memberTbService.xghyjs(member.getId(), member.getRolezd(), memberDz.getId()));
    	
    }
    
    // /h5/shop
    @ApiOperation("新增会员积分流水")
    @PostMapping("/act/in/insert") //subOpType 15：加 16：减  amount多少积分  memberId会员id  bz备注
    public ResponseEntity<Integer> actInInsert(@RequestBody IntegralHistory integralHistory) {
    	checkMember(integralHistory.getMemberId());
        Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        int subOpType = integralHistory.getSubOpType().intValue();
        if(subOpType != 15 && subOpType != 16) {
            throw new RuntimeException("不支持的类型！"+subOpType);
    	}
        Integer num =  integralHistoryService.handleIntegralMain(integralHistory.getSubOpType(), integralHistory.getAmount(), integralHistory.getMemberId(), member.getId(), integralHistory.getBz());
        return ResponseEntity.ok(num);
    }


    

	   @ApiOperation("订单统计") //  /h5/shop
	    @GetMapping("/aws/systemStatistics") //1今日  2昨天  3本月 5本年 9全部
	    public ResponseEntity<SystemStatistics> systemStatistics(String dateType){
	        
	    	Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
	        Long deptZbjId = member.getDeptZbjId();
	        Long deptTzId = member.getDeptTzId();
	        Long deptDpId = member.getDeptDpId();
	        if(deptZbjId==null || deptTzId==null || deptDpId==null || dateType==null) {
	        	return ResponseEntity.ok(new SystemStatistics());
	        }
	        

	        LocalDateTime startTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
			LocalDateTime endTime  = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
			if("1".equals(dateType)) {//今日
		         startTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
				 endTime = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
			}	
			if("2".equals(dateType)) {//昨天
		         startTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).plusDays(-1);
				 endTime = LocalDateTime.of(LocalDate.now(), LocalTime.MAX).plusDays(-1);
			}
			System.err.println("dateType: " +dateType + " s: "+startTime  + " e:" + endTime);
			if("1".equals(dateType) || "2".equals(dateType)) {//今日
			 	SystemStatistics data = systemStatisticsService.stat(deptZbjId, deptTzId, deptDpId, startTime, endTime);
		        return ResponseEntity.ok(data);
			}
			startTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).plusDays(-1);
			endTime = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
			
		 	SystemStatistics thisData = systemStatisticsService.stat(deptZbjId, deptTzId, deptDpId, startTime, endTime);

			if("3".equals(dateType)) {//本月
		         startTime = LocalDateTime.now().toLocalDate().withDayOfMonth(1).atStartOfDay();
				 endTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).plusDays(-1);
			}
			
			if("5".equals(dateType)) {//本年
		         startTime = LocalDateTime.now().toLocalDate().withDayOfYear(1).atStartOfDay();
				 endTime = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).plusDays(-1);
			}
			
			if("9".equals(dateType)) {//全部
		         startTime = null;
				 endTime = null;
			}
	    	

			
			SystemStatisticsQuery query = new SystemStatisticsQuery();
			query.setDeptZbjId(deptZbjId);
			query.setDeptTzId(deptTzId);
			query.setDeptDpId(deptDpId);
			query.setBeginTime(startTime);
			query.setEndTime(endTime);
			query.setType("3");
			query.setSfDate("false");
			PageImpl<SystemStatistics> page = systemStatisticsService.selectList(query, null);
			List<SystemStatistics> list = page.getContent();
			if(list!=null && list.size()>0) {
				SystemStatistics dbData = list.get(0);
		        return ResponseEntity.ok(SystemStatistics2Convert.dosAdddos(thisData, dbData));
			}
	    	return ResponseEntity.ok(thisData);
	    }
	   

	  
	    private void setCacheShopStat(String dateType,Long ckDeptDpId,Long spreaduid,ShopStatistics shopStatisticsCache,LocalDateTime strTime,LocalDateTime endTime){
	    	if(shopStatisticsCache!=null) {
	    		QueryWrapper<Member> queryWrapper = new QueryWrapper<Member>();
				queryWrapper.between("spread_time", strTime, endTime);
				queryWrapper.eq("dept_dp_id", ckDeptDpId);
				if(spreaduid!=null) {
					queryWrapper.eq("spreaduid", spreaduid);
				}
				shopStatisticsCache.setMemberDayConut(memberMapper.selectCount(queryWrapper));
	    	}
	       	String shopStatKey = "SHOP_STAT_"+dateType+"_"+ckDeptDpId+"_"+spreaduid;
	        redisCache.setCacheObject(shopStatKey, shopStatisticsCache, 10, TimeUnit.SECONDS);
	    }
	    
	    private ShopStatistics getCacheShopStat(String dateType,Long ckDeptDpId,Long spreaduid){
	       	String shopStatKey = "SHOP_STAT_"+dateType+"_"+ckDeptDpId+"_"+spreaduid;
	       	return redisCache.getCacheObject(shopStatKey);
	    }
	   
	    @ApiOperation("订单统计") //  /h5/shop
	    @GetMapping("/aws/systemStatistics2") //1今日  2昨天  3本月 5本年 9全部
	    public ResponseEntity<ShopStatistics> systemStatistics2(String dateType,Long ckDeptDpId,Long spreaduid){
	    	if(spreaduid==null) {
	    		spreaduid = getSpreaduid();
	    	}
	        if(ckDeptDpId == null) {
		    	Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
		    	ckDeptDpId =  member.getDeptDpId();
	        }
	        ShopStatistics shopStatisticsCache =  getCacheShopStat(dateType, ckDeptDpId,spreaduid);
	        if(shopStatisticsCache!=null) {
		    	return ResponseEntity.ok(shopStatisticsCache);
	        }
	        return systemStatistics3(dateType, ckDeptDpId,spreaduid);
	     
	        
//	    	Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
//	        Long deptDpId = member.getDeptDpId();
//	        if(checkDzQtmd(ckDeptDpId)) {//查看其他店铺数据
//	        	deptDpId = ckDeptDpId;
//	        }
//	        if(deptDpId==null || dateType==null) {
//	        	return ResponseEntity.ok(null);
//	        }
//	        ShopStatistics shopStatisticsCache =  getCacheShopStat(dateType, deptDpId);
//	        if(shopStatisticsCache!=null) {
//		    	return ResponseEntity.ok(shopStatisticsCache);
//	        }
//	        
//	        LocalDate thisDate = LocalDate.now();
//	        LocalDateTime strTime = LocalDateTime.of(thisDate, LocalTime.MIN);
//	 		LocalDateTime endTime  = LocalDateTime.of(thisDate, LocalTime.MAX);
//	 		ShopStatistics shopStatistics = shopStatisticsService.selectShopToDayByDeptDpId(deptDpId);
//	 		
//	 		
//	 		if("1".equals(dateType)) {//今日
//	 			setCacheShopStat(dateType, deptDpId, shopStatistics,strTime,endTime);
//	 			return ResponseEntity.ok(shopStatistics);
//			}	
//	 	
//			endTime = LocalDateTime.of(thisDate, LocalTime.MAX).plusDays(-1);
//
//			if("2".equals(dateType)) {//昨天
//				 strTime = LocalDateTime.of(thisDate, LocalTime.MIN).plusDays(-1);
//			} 
//			if("3".equals(dateType)) {//本月
//				 strTime = LocalDateTime.now().toLocalDate().withDayOfMonth(1).atStartOfDay();
//			}
//			
//			if("5".equals(dateType)) {//本年
//				 strTime = LocalDateTime.now().toLocalDate().withDayOfYear(1).atStartOfDay();
//			}
//			
//			if("9".equals(dateType)) {//全部
//				 strTime = DateUtil.parseLocalDateTime("2025-01-01 00:00:00");
//			}
//			
//			ShopStatisticsQuery query = new ShopStatisticsQuery();
////			query.setDeptZbjId(deptZbjId);
////			query.setDeptTzId(deptTzId);
//			query.setDeptDpId(deptDpId);
//			query.setByColumn(null);
//			query.setType("3");
//			query.setSfDate("false");
//			query.setTjdataRange(new Integer[] {
//				Integer.parseInt(DateUtil.format(strTime, "yyyyMMdd")),
//				Integer.parseInt(DateUtil.format(endTime, "yyyyMMdd"))
//			});
//	 	
//			
//			List<ShopStatistics> list = shopStatisticsService.selectList(query, null);
//			if(list!=null && list.size()>0) {
//				ShopStatistics dbData = list.get(0);
//				if("2".equals(dateType)) {//昨天
//		 				setCacheShopStat(dateType, deptDpId, dbData,strTime,endTime);
//			    		return ResponseEntity.ok(dbData);
//				}
//				ShopStatistics retShopStatistics = ShopStatistics2Convert.dosAdddos(shopStatistics, dbData);
//				setCacheShopStat(dateType, deptDpId, retShopStatistics,strTime,LocalDateTime.of(thisDate, LocalTime.MAX));
//		        return ResponseEntity.ok(retShopStatistics);
//			}
//			setCacheShopStat(dateType, deptDpId, shopStatistics,strTime,LocalDateTime.of(thisDate, LocalTime.MAX));
//	    	return ResponseEntity.ok(shopStatistics);
	    }
	   
	    
	    @ApiOperation("订单统计") //  /h5/shop
	    @GetMapping("/aws/systemStatistics3") //1今日  2昨天  3本月 5本年 9全部
	    public ResponseEntity<ShopStatistics> systemStatistics3(String dateType,Long ckDeptDpId,Long spreaduid){
	        
//	    	Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
//	        Long deptDpId = member.getDeptDpId();
//	       
//	        if(deptDpId==null || dateType==null) {
//	        	return ResponseEntity.ok(null);
//	        }
	     
	        LocalDate thisDate = LocalDate.now();
	        LocalDateTime strTime = LocalDateTime.of(thisDate, LocalTime.MIN);
	 		LocalDateTime endTime  = LocalDateTime.of(thisDate, LocalTime.MAX);
	 		

	 		
	 		if("1".equals(dateType)) {//今日
	 			strTime = LocalDateTime.of(thisDate, LocalTime.MIN);
			}	

			if("2".equals(dateType)) {//昨天
				 strTime = LocalDateTime.of(thisDate, LocalTime.MIN).plusDays(-1);
				 endTime  = LocalDateTime.of(thisDate, LocalTime.MAX).plusDays(-1);
			} 
			
			if("3".equals(dateType)) {//本月
				 strTime = LocalDateTime.now().toLocalDate().withDayOfMonth(1).atStartOfDay();
			}
			
			if("5".equals(dateType)) {//本年
				 strTime = LocalDateTime.now().toLocalDate().withDayOfYear(1).atStartOfDay();
			}
			
			if("9".equals(dateType)) {//全部
				 strTime = DateUtil.parseLocalDateTime("2025-01-01 00:00:00");
			}
			
	 		ShopStatistics shopStatistics = shopStatisticsService.selectShopToDayByDeptDpId3(ckDeptDpId, spreaduid, strTime, endTime);
	 		if(shopStatistics==null) {
	 			shopStatistics = new ShopStatistics();
	 		}
	 		ShopStatistics retShopStatistics = new ShopStatistics(shopStatistics);
	 	    setCacheShopStat(dateType, ckDeptDpId,spreaduid, retShopStatistics,strTime,endTime);
	    	return ResponseEntity.ok(retShopStatistics);
 
	    }
	   

	//@ApiOperation("查询优惠券活动表列表") ///h5/shop
    @PostMapping("/act/couponActivity/list")
    public ResponseEntity<Page<CouponActivityVO>> list(@RequestBody CouponActivityQuery query, Pageable page) {
    	Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        Long deptDpId = member.getDeptDpId();
        query.setPublishstatus(1);
        if(deptDpId!=null) {
        	query.setDeptDpId(deptDpId);
        }
        return ResponseEntity.ok(couponActivityService.selectList(query, page));
    }
		    
    
    // /h5/shop///h5/shop
//    @ApiOperation("新增会员福利券") 
    @PostMapping("/act/couponActivity/insert") // 券id couponActivityId; 用户id  memberId; 发多少张   num;
    public ResponseEntity<Boolean> couponActivityInsert(@RequestBody AddAcForm addAcForm) {
    	Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        Long deptDpId = member.getDeptDpId();
    	checkMember(addAcForm.getMemberId());
        boolean num =  couponActivityService.dzFfByFlq(addAcForm.getCouponActivityId(), addAcForm.getMemberId(), addAcForm.getNum(),deptDpId);
        return ResponseEntity.ok(num);
    }
	
	//@ApiOperation("查询积分信息") ///h5/shop
	 @GetMapping("/ums/memberAccount/get")
	 public ResponseEntity<MemberAccount> getMemberAccount(Long memberId) {
	     checkMember(memberId);
	     return ResponseEntity.ok(memberAccountService.selectByMemberId(memberId));
	 }
	 
	// 店铺订单统计
    @PostMapping("/oms/orderItem/findDpOrderTj")
    public ResponseEntity<Page<OrderItemDptjVO>> findDpOrderTj(@RequestBody OrderItemDptjQuery query, Pageable page) {
    	Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        Long deptDpId = member.getDeptDpId();
        if(deptDpId!=null) {
        	query.setDeptDpId(deptDpId);
        }
        Long spreaduid = query.getSpreaduid(); 
    	if(spreaduid!=null) {
    		query.setSpreaduid(spreaduid);
    	}else {
    		query.setSpreaduid(getSpreaduid());
    	}
        List<OrderItemDptjVO> list = orderItemService.findDpOrderTj(query, page);
        return ResponseEntity.ok(new PageImpl<>(list, page, ((com.github.pagehelper.Page)list).getTotal()));
    }   
   
    @ApiOperation("店长申请售后") ///h5/shop
    @PostMapping("/oms/order/applyRefund")
    public ResponseEntity<Boolean> applyRefund(@RequestBody ApplyRefundForm applyRefundForm){
    	 Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
         Long qrDeptZbjId = member.getDeptZbjId();
  	     String existJobInfo = redisCache.getCacheObject("order_export_lock_key"+qrDeptZbjId);
         if (StringUtils.isNotEmpty(existJobInfo)) {
        	 throw new RuntimeException("导单中，请稍后重试！");
         }
         Order orderDb = orderMapper.selectById(applyRefundForm.getOrderId());
     	 checkMember(orderDb.getMemberId());
     	String description  = applyRefundForm.getDescription();
     	description = "店铺申请退款：" + description;
     	applyRefundForm.setDescription(description);
     	
        String redisKey = "h5_oms_order_applyRefund_" + applyRefundForm.getOrderId();
        String redisValue = applyRefundForm.getOrderId() + "_" + System.currentTimeMillis();
        try{
            redisService.lock(redisKey, redisValue, 60);
            Order order = h5OrderService.applyRefund(applyRefundForm,false);
            if (order.getLockId() == null) {
                DealWithAftersaleForm req = new DealWithAftersaleForm();
                req.setOrderId(applyRefundForm.getOrderId());
                req.setOptType(1);
                aftersaleService.dealWith(req, order.getMemberId(), "未锁单店铺发起退款");
            }
            return ResponseEntity.ok(true);
        }catch (Exception e){
            log.error("申请售后发生异常",e);
            throw new RuntimeException(e.getMessage());
        }finally {
            try {
                redisService.unLock(redisKey, redisValue);
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }
    
	
	//获取店长的其他店铺信息
	 @GetMapping("/qtdp/getQtdplist")
	 public ResponseEntity<List<SysDept>> getQtdplist() {
    	Member dzMember = SecurityUtil.getLocalMember();
    	List<SysDept> sysList = new ArrayList<SysDept>();
    	String stDeptDpIds = dzMember.getQtDeptDpIds();
		if(stDeptDpIds!=null && !"".equals(stDeptDpIds)) {
	    	List<Long> ids = new ArrayList<Long>();
			String[] qtIds =  stDeptDpIds.split(",");
			for (String dpid : qtIds) {
				ids.add(Long.parseLong(dpid));
			}
			QueryWrapper<SysDept> queryWrapper = new QueryWrapper<SysDept>();
			queryWrapper.select("dept_id,dept_name,address, bmlx, province, city ,district ,leader, phone");
			queryWrapper.in("dept_id", ids);
			queryWrapper.eq("del_flag", "0");
			sysList = sysDeptMapper.selectList(queryWrapper);
		}
	    return ResponseEntity.ok(sysList);
	 }
    
	 @GetMapping("/memberCoupon/selectMemberCouponGrepDp")
	 public ResponseEntity<Page<MemberCouponTjVO>> selectMemberCouponGrepDp(Long memberId,Long spreaduid,Pageable page) {
		    if (page != null) {
	            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
	        }
	    	Member dzMember = SecurityUtil.getLocalMember();
	    	Long deptDpId = dzMember.getDeptDpId();
	    	if(deptDpId==null) {
	    		  return ResponseEntity.ok(null);
	    	}
//	    	if(memberId!=null) {
//		    	checkMember(memberId);
//	    	}
		 	MemberCouponTjQuery mctq = new MemberCouponTjQuery();
		 	mctq.setDeptDpId(dzMember.getDeptDpId());
		 	mctq.setMemberId(memberId);
	    	if(spreaduid!=null) {
	    		mctq.setSpreaduid(spreaduid);
	    	}else {
	    		mctq.setSpreaduid(getSpreaduid());
	    	}
		 	List<MemberCouponTjVO> list = (memberCouponMapper.selectMemberCouponGrepDp(mctq));
		 	if(list==null || list.size()==0) {
		        return ResponseEntity.ok(new PageImpl<MemberCouponTjVO>(list, page, 0));
		 	}
		 	long total = list.size();
		 	try {
		 		total = ((com.github.pagehelper.Page) list).getTotal();
			} catch (Exception e) {
			}
		   return ResponseEntity.ok(new PageImpl<MemberCouponTjVO>(list, page, total));
	 }
	    
	 @GetMapping("/memberCoupon/selectMemberCouponGrepMember") 
	 public ResponseEntity<Page<MemberCouponTjVO>> selectMemberCouponGrepMember(Long couponCategoryId,Long spreaduid,Long memberId,Pageable page) {
		    if (page != null) {
	            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
	        }
	    	Member dzMember = SecurityUtil.getLocalMember();
	    	Long deptDpId = dzMember.getDeptDpId();
	    	if(deptDpId==null || couponCategoryId == null) {
	    		  return ResponseEntity.ok(null);
	    	}
//	    	if(memberId!=null) {
//		    	checkMember(memberId);
//	    	}
		 	MemberCouponTjQuery mctq = new MemberCouponTjQuery();
		 	mctq.setDeptDpId(dzMember.getDeptDpId());
		 	mctq.setCouponCategoryId(couponCategoryId);
		 	mctq.setMemberId(memberId);
		 	if(spreaduid!=null) {
	    		mctq.setSpreaduid(spreaduid);
	    	}else {
	    		mctq.setSpreaduid(getSpreaduid());
	    	}
		 	List<MemberCouponTjVO> list = (memberCouponMapper.selectMemberCouponGrepMember(mctq));
		 	if(list==null || list.size()==0) {
		        return ResponseEntity.ok(new PageImpl<MemberCouponTjVO>(list, page, 0));
		 	}
		 	long total = list.size();
		 	try {
		 		total = ((com.github.pagehelper.Page) list).getTotal();
			} catch (Exception e) {
			}
	        return ResponseEntity.ok(new PageImpl<MemberCouponTjVO>(list, page, total));

	 }
	    
	 
	 
	@ApiOperation("查询意见反馈列表") ///h5/shop
    @PostMapping("/ums/feedback/list")
    public ResponseEntity<Page<Feedback>> list(@RequestBody FeedbackQuery query, Pageable page) {
		Member dzMember = SecurityUtil.getLocalMember();
    	Long deptDpId = dzMember.getDeptDpId();
    	if(deptDpId==null) {
    		  return ResponseEntity.ok(null);
    	}
	    query.setType("2");
	    query.setDeptDpId(deptDpId); 
	    Long spreaduid = query.getSpreaduid(); 
    	if(spreaduid!=null) {
    		query.setSpreaduid(spreaduid);
    	}else {
    		query.setSpreaduid(getSpreaduid());
    	}
    	List<Feedback> list = feedbackService.selectList(query, page);
        return ResponseEntity.ok(new PageImpl<>(list, page, ((com.github.pagehelper.Page)list).getTotal()));
    }
	
	

	
	
	@ApiOperation("统计支付未退款的店铺订单")
    @PostMapping("/oms/order/selectShopHxProductTj")
    public ResponseEntity<List<ManagerOrderVO>> selectShopHxProductTj(@RequestBody ManagerOrderQueryForm query) {
    	Member member = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        query.setDeptDpId(member.getDeptDpId());
        Long spreaduid = query.getSpreaduid(); 
    	if(spreaduid!=null) {
    		query.setSpreaduid(spreaduid);
    	}else {
    		query.setSpreaduid(getSpreaduid());
    	}
    	List<ManagerOrderVO> list = h5OrderService.selectShopHxProductTj(query);
        return ResponseEntity.ok(list);    	
    }
    
    
    @ApiOperation("修改会员基本信息")
    @PostMapping("/ums/member/updateJbxx")
    public ResponseEntity<Integer> updateJbxx(@RequestBody Member member){
        Member memberDb = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        checkMember(memberDb.getId());
        return ResponseEntity.ok(h5MemberService.updateJbxx(member,true));
    }
		
    
	@ApiOperation("获取后台给店铺发的未过期的福利券") ///h5/shop
	@GetMapping("/act/couponActivity/selectDpActivityList")
    public ResponseEntity<List<CouponActivity>> selectDpActivityList() {
		Member dzMember = SecurityUtil.getLocalMember();
    	Long deptDpId = dzMember.getDeptDpId();
    	if(deptDpId==null) {
    		  return ResponseEntity.ok(null);
    	}
    	CouponActivityQuery query = new CouponActivityQuery();
	    query.setDeptDpId(deptDpId); 
        List<CouponActivity> list = h5CouponActivityService.selectDpActivityList(query);
        return ResponseEntity.ok(list);
    }
	
	
	@ApiOperation("根据Id获取店铺的福利券剩余数量")
    @PostMapping("/act/couponActivity/selectCountByActivityId")
    public ResponseEntity<CouponActivity> selectCountByActivityId(Long couponActivityId) {
        return ResponseEntity.ok(h5CouponActivityService.selectCountByActivityId(couponActivityId));
    }
	
	@ApiOperation("修改地址")
    @PostMapping("/dept/update/address")
    public ResponseEntity<String> updateAddress(@RequestBody H5AddressVO vo) {
		SysDept sysDept = new SysDept();
		sysDept.setDeptId(vo.getDeptId());
		sysDept.setLeader(vo.getLeader());
		sysDept.setPhone(vo.getPhone());
		sysDept.setProvince(vo.getProvince());
		sysDept.setCity(vo.getCity());
		sysDept.setDistrict(vo.getDistrict());
		sysDept.setAddress(vo.getAddress());
		deptMapper.updateDept(sysDept);
		deptService.delCacheSysDept2(vo.getDeptId());
        return ResponseEntity.ok("成功！");
    }
	
    @ApiOperation("修改会员备注信息")
    @PostMapping("/ums/member/mark/update")
    public ResponseEntity<Integer> editMark(@RequestBody Member member) {
        Member memberDb = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        member.setId(memberDb.getId());
        return ResponseEntity.ok(memberService.updateMark(member));
    }
    
    @ApiOperation("设置店长的其他店铺部门id")
    @PutMapping("/ums/member/updateByDzqtDpid")
    public ResponseEntity<Integer> updateByDzqtDpid(@RequestBody Member member) {
        Member memberDb = (Member) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        member.setId(memberDb.getId());
        return ResponseEntity.ok(memberService.updateByDzqtDpid(member.getId(),member.getQtDeptDpIds()));
    }


    
    public void checkMember(Long memberId) {
    	Member member = memberService.selectById(memberId);
    	if(member != null) {
    		if(SecurityUtil.getLocalMember().getDeptDpId().longValue() != member.getDeptDpId().longValue()) {
                throw new RuntimeException("不能操作非自己店铺客户数据！");
        	}
    	}
    	
    }
    
	   
    public void checkMemberV2(Long memberId) {
    	Member dzMember = SecurityUtil.getLocalMember();
    	long gkDeptDpId = 0;
    	try {
       	 	gkDeptDpId = memberService.selectById(memberId).getDeptDpId().longValue();
		} catch (Exception e) {
			  throw new RuntimeException("不能操作非自己店铺客户数据！");
		}
    	if(dzMember.getDeptDpId().longValue() != gkDeptDpId) {
    		boolean sfqtdp = false;
    		String stDeptDpIds = dzMember.getQtDeptDpIds();
    		if(stDeptDpIds!=null) {
    			String[] qtIds =  stDeptDpIds.split(",");
    			for (String dpids : qtIds) {
					if(Long.parseLong(dpids) == gkDeptDpId) {
						sfqtdp = true;
					}
				}
    		}
    		if(sfqtdp == false) {
                throw new RuntimeException("不能操作非自己店铺客户数据！");
    		}
    	}
    }
    
    /**
     * 	判断此店长是否有权限查看此店铺的数据
     * @param ckDeptDpId
     */
    public boolean checkDzQtmd(Long ckDeptDpId) {
    	boolean sfqtdp = false;
    	if(ckDeptDpId==null) {
    		return sfqtdp;
    	}
    	long gkDeptDpId = ckDeptDpId.longValue();
    	Member dzMember = SecurityUtil.getLocalMember();
    	if(dzMember.getDeptDpId().longValue() != gkDeptDpId) {
    		String stDeptDpIds = dzMember.getQtDeptDpIds();
    		if(stDeptDpIds!=null) {
    			String[] qtIds =  stDeptDpIds.split(",");
    			for (String dpids : qtIds) {
					if(Long.parseLong(dpids) == gkDeptDpId) {
						sfqtdp = true;
					}
				}
    		}
    	}else {
    		sfqtdp = true;
    	}
		return sfqtdp;
    }
    
    
  
    
    
}
